如何判斷在 JS 當中找出它屬於哪一類呢?
也許是因爲 JS 變數是動態型別,因此得知變數爲哪一個純值類型或物件類型,在許多書及文章中總是被熱烈討論。那麼今天就用一些簡單的方式來看看該如何得知吧。
嘗試方法前我們先產生一些變數類型用以測試:
var aNumber = 5;
var aString ="hi";
var aArray = [1,2,3];
var aBoolean = true;
var aUndefined = undefined;
var aNull = null;
var aObject = {name:"Lai"};
function aFunction(){
console.log("hehe");
}
console.log(typeof aNumber); //number
console.log(typeof aString); //string
console.log(typeof aArray); //object
console.log(typeof aBoolean); //boolean
console.log(typeof aUndefined); //undefined
console.log(typeof aNull); //object 傳說中的bug
console.log(typeof aObject); //object
console.log(typeof aFunction); //function
console.log(aNumber instanceof Number); //false
console.log(aString instanceof String); //false
console.log(aArray instanceof Array); //true
console.log(aArray instanceof Object); //true
console.log(aBoolean instanceof Boolean); //false
console.log(aUndefined instanceof Undefined); //報錯
console.log(aNull instanceof Object); //false
console.log(aObject instanceof Object); //true
console.log(aFunction instanceof Function); //true
console.log(aFunction instanceof Object); //true
方法二可以說是爲解物件而生,可以解方法一看不出 Array,這個方法很適合物件,通常用來判斷一個實例是否屬於某種類型。
var aFunction2 = new aFunction();
console.log(aFunction2 instanceof aFunction); //true
到這邊可以分個界線 typeof 判斷純值,instanceof 判斷非純值。
最單純,而且很準確。
console.log(Object.prototype.toString.call(aNumber)); //[object Number]
console.log(Object.prototype.toString.call(aString)); //[object String]
console.log(Object.prototype.toString.call(aArray)); //[object Array]
console.log(Object.prototype.toString.call(aBoolean)); //[object Boolean]
console.log(Object.prototype.toString.call(aUndefined)); //[object Undefined]
console.log(Object.prototype.toString.call(aNull)); //[object Null]
console.log(Object.prototype.toString.call(aObject)); //[object Object]
console.log(Object.prototype.toString.call(aFunction)); //[object Function]
以上是今天關於你是誰的小探討。